//
//  NSArray+Swizzling.m
//  xk100
//
//  Created by xiaokang on 2017/5/22.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#import "NSArray+Swizzling.h"
#import "NSObject+Swizzling.h"

@implementation NSArray (Swizzling)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [objc_getClass("__NSArrayI") yg_methodSwizzlingWithOriginalSelector:@selector(objectAtIndex:) bySwizzledSelector:@selector(safeObjectAtIndex:)];
        [objc_getClass("__NSArrayI") yg_methodSwizzlingWithOriginalSelector:@selector(objectsAtIndexes:) bySwizzledSelector:@selector(safeObjectAtIndexes:)];
        [objc_getClass("__NSArrayI") yg_methodSwizzlingWithOriginalSelector:@selector(subarrayWithRange:) bySwizzledSelector:@selector(safeSubarrayWithRange:)];
    });
 
}

- (id)safeObjectAtIndex:(NSInteger)index {
    if (self.count == 0) {
        NSLog(@"❌❌❌%s can't get any object from an empty array", __FUNCTION__);
        return nil;
    }
    if (index > self.count) {
        NSLog(@"❌❌❌%s index out of bounds in array", __FUNCTION__);
        return nil;
    }
    return [self safeObjectAtIndex:index];
}

- (id)safeObjectAtIndexes:(NSIndexSet *)indexSet {
    NSArray *returnArray = nil;
    @try {
        returnArray = [self safeObjectAtIndexes:indexSet];
    } @catch (NSException *exception) {
        // 在崩溃后会打印崩溃信息。如果是线上，可以在这里将崩溃信息发送到服务器
        NSLog(@"❌❌❌异常名称:%@\n❌❌❌异常原因:%@",exception.name, exception.reason);
        returnArray = nil;
    } @finally {
        return returnArray;
    }
}

- (id)safeSubarrayWithRange:(NSRange *)range;  {
    NSArray *returnArray = nil;
    @try {
        returnArray = [self safeSubarrayWithRange:range];
    } @catch (NSException *exception) {
        // 在崩溃后会打印崩溃信息。如果是线上，可以在这里将崩溃信息发送到服务器
        NSLog(@"❌❌❌异常名称:%@\n❌❌❌异常原因:%@",exception.name, exception.reason);
        NSLog(@"%@", [exception callStackSymbols]);
        returnArray = nil;
    } @finally {
        return returnArray;
    }
}
@end
